package com.bjpowerrnode.streamTest;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ICollectors {
    public static void main(String[] args) {
        /**
         * Collectors 类实现了很多归约操作，例如将流转换成集合和聚合元素。Collectors 可用于返回列表或字符串：
         */
        List<String> stringList = Arrays.asList("abc","", "123","", "ijk", "456");
        List<String> collect = stringList.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList());
        collect.forEach(System.out::println);
        /**Collectors.joining()*/
        System.out.println("============Collectors.joining()================");
        String collect1 = stringList.stream().filter(s -> !s.isEmpty()).collect(Collectors.joining());
        System.out.println(collect1);
        /** Collectors.toMap()*/
        System.out.println("============Collectors.toMap()================");
        Student student1 = new Student(2,"sun");
        Student student2 = new Student(2,"xue");
        Student student3 = new Student(3,"teng");
        List<Student> students = new ArrayList<>();
        students.add(student1);
        students.add(student2);
        students.add(student3);
        students.forEach(System.out::println);
        System.out.println("=================================");
        // 当key相同时时候后一个value
        Map<Integer, Student> map1 = students.stream()
                .collect(Collectors.toMap(Student::getId, o -> o,(v1,v2)->v2));
        map1.forEach((integer, student) -> System.out.println(integer+student.toString()));
        Map<Integer, Student> map2 = students.stream()
                .collect(Collectors.toMap(Student::getId, Function.identity(),(v1,v2)->v1));
        Map<Integer, String> map3 = students.stream()
                .collect(Collectors.toMap(Student::getId, Student::getName,(v1,v2)->v1));
        System.out.println("===================================");
        map3.forEach((key,value)-> System.out.println("key="+key+";value="+value));

    }
}
